export default {
  data() {
    return {
      url: '',
      id: '',
      listURL: '',
      rules: {},
      record: {},
    }
  },
  methods: {
    loadData() {
      if (this.accessType === 'create') {
        return
      }
      this.$httpGet(`${this.url}/${this.id}`).then((response) => {
        this.record = response.data
        this.afterLoadData(this.record)
      }).catch(() => {})
    },
    afterLoadData(record) {},
    beforeSave() {},
    save() {
      this.beforeSave()
      this.$refs.record.validate((valid) => {
        if (!valid) {
          return
        }
        if (this.accessType === 'create') {
          this.$httpPost(this.url, this.record).then(() => {
            this.$message.success('新建成功')
            this.$router.push(this.listURL || this.url)
          }).catch(() => {})
        } else {
          this.$httpPut(`${this.url}/${this.id}`, this.record).then(() => {
            this.$message.success('编辑成功')
            this.$router.push(this.listURL || this.url)
          }).catch(() => {})
        }
      })
    },
  },
  created() {
    this.accessType = this.$route.query.operation
    this.id = this.$route.params.id || ''
    this.loadData()
  },
  computed: {
    accessTitle() {
      switch (this.accessType) {
        case 'view':
          return '详情'
        case 'create':
          return '新建'
        case 'edit':
          return '编辑'
        default:
          return '详情'
      }
    },
    disabled() {
      return this.$route.query.operation !== 'edit' && this.$route.query.operation !== 'create'
    },
  },
}
